package com.xnx3.banmahuishou.agency.controller;

import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xnx3.DateUtil;
import com.xnx3.banmahuishou.core.entity.Agency;
import com.xnx3.banmahuishou.core.entity.MoneyChangeRecord;
import com.xnx3.banmahuishou.core.entity.RechargeLog;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.core.entity.WeixinPublicDlsOpenid;
import com.xnx3.banmahuishou.core.util.AppUtil;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.weixin.weixinPay.PayCallBackParamsVO;
import com.xnx3.weixin.weixinPay.v2.NativePay;

import net.sf.json.JSONObject;

/**
 * 财务管理
 * @author 王晓龙
 */
@Controller(value="BanmahuishouAgencyFinanceController")
@RequestMapping("/agency/finance/")
public class FinanceController extends BaseController  {
    @Resource
    private SqlService sqlService;

    static NativePay pay;	//微信支付
    static {
        pay = new NativePay();
        //微信支付的商户号，格式如：1581125900 ，登录 https://pay.weixin.qq.com/ 取得
        pay.mch_id = "1616291102";	
        //微信支付的API密钥，32位字符串。登录 https://pay.weixin.qq.com/ 在 [账户中心] - [API安全] - [设置API密钥]
        pay.mch_key = "Banmahuishou963258banxmagongzhon";	
        //微信公众号的appid，格式如 wx07f3db3a6bbexxxx
        pay.gongzhonghao_appid = "wxbdb3e50bee354370";
        //微信公众号的 appsecret ，格式如 b067bdd3935962ff8262f51fe5054xxx
        pay.gongzhonghao_appsecret = "a982dbff8974eece711db294d8ca4026";
        //微信支付成功后，微信服务器会将支付结果异步通知我们的服务器。这里是异步通知的url。传入如 http://xxx.zvo.cn/weixin.do
        pay.notify_url = "https://app.banxma.com/agency/finance/callback.do";
        //		pay.notify_url = "http://9jyieb.natappfree.cc/agency/finance/callback.do";
    }



    /**
     * 分配金额列表
     */
    @RequestMapping("list${url.suffix}")
    public String list(HttpServletRequest request,Model model){
        Sql sql = new Sql(request);
        sql.setSearchColumn(new String[]{"name"});
        sql.appendWhere("state = " + Wangge.STATE_NORMAL +" AND dailishang_userid = " + getUserId());
        int count = sqlService.count("laji_wangge", sql.getWhere());
        Page page = new Page(count, 15, request);
        sql.setSelectFromAndPage("SELECT * FROM laji_wangge", page);
        sql.setDefaultOrderBy("laji_wangge.id DESC");
        List<Wangge> list = sqlService.findBySql(sql, Wangge.class);
        String sqlAgency = "SELECT * FROM laji_agency WHERE userid=" + getUserId();
        Agency agency = sqlService.findAloneBySqlQuery(sqlAgency, Agency.class);

        ActionLogUtil.insert(request, "财务管理", "第"+page.getCurrentPageNumber()+"页");

        model.addAttribute("money",agency.getMoney());
        model.addAttribute("page", page);
        model.addAttribute("list", list);
        return "/agency/finance/list";
    }




    /**
     * 跳转给网格分配金额的页面
     * @param wanggeUserid		网格后台用户id
     */
    @RequestMapping("goDistributionAmount${url.suffix}")
    public String goDistributionAmount(HttpServletRequest request,Model model,
        @RequestParam(value = "wanggeUserid",required = true,defaultValue = "0") Integer wanggeUserid){

        model.addAttribute("wanggeUserid", wanggeUserid);
        ActionLogUtil.insert(request, "跳转给网格分配金额的页面", "要给网格ID为: " + wanggeUserid + "的网格分配金额");

        return "/agency/finance/goDistributionAmount";
    }


    /**
     * 给网格分配金额
     * @param wanggeUserid	网格后台用户id
     * @param money			分配的金额,单位:分
     */
//    @Transactional
    @ResponseBody
    @RequestMapping("distributionAmount${api.suffix}")
    public BaseVO distributionAmount(HttpServletRequest request,
        @RequestParam(value = "wanggeUserid",required = true,defaultValue = "0") Integer wanggeUserid,
        @RequestParam(value = "money",required = true,defaultValue = "0") Integer money){

        if (wanggeUserid <= 0) {
            return error("请选择被分配金额的网格");
        }
        if (money <= 0) {
            return error("请输入分配金额");
        }
        if (money - 1 < 0) {
            return error("最低分配金额为0.01元");
        }
        int userId = getUserId();
        // 查询要代理商用户信息
        User dlsUser = sqlService.findById(User.class, userId);
        if (dlsUser == null ) {
            return notLogin();
        }
        // 代理商延伸表
        Agency agency = sqlService.findAloneByProperty(Agency.class, "userid", dlsUser.getId());
        if (agency == null ) {
            return notLogin();
        }
        // 查询要被分配网格用户信息
        User wgUser = sqlService.findById(User.class, wanggeUserid);
        if (wgUser == null) {
            return error("网格用户信息错误");
        }
        // 网格延伸表
        Wangge wangge = sqlService.findAloneByProperty(Wangge.class, "id", wgUser.getId());
        if (wangge == null) {
            return error("网格用户信息错误");
        }
        // 代理商分配之前的余额
        Integer dlsMoney = dlsUser.getMoney() == null ? 0 : dlsUser.getMoney();
        if (dlsMoney < money) {
            return error("余额不足,请先充值!");
        }
        // 给网格添加分配的金额
        Integer wgMoney = wgUser.getMoney() == null ? 0 : wgUser.getMoney();
        wgUser.setMoney(wgMoney + money);
        sqlService.save(wgUser);
        // 给网格更新金额
        wangge.setMoney(wgUser.getMoney());
        sqlService.save(wangge);
        // 给代理商用户减去金额
        dlsUser.setMoney(dlsMoney - money);
        sqlService.save(dlsUser);
        // 给代理商更新金额
        agency.setMoney(dlsUser.getMoney());
        sqlService.save(agency);
        // 添加代理商的金额变更记录
        MoneyChangeRecord changeRecord = new MoneyChangeRecord();
        changeRecord.setCreateTime(DateUtil.timeForUnix10());
        changeRecord.setMoney(dlsUser.getMoney() - dlsMoney);
        changeRecord.setPhone(dlsUser.getPhone());
        changeRecord.setUserId(dlsUser.getId());
        changeRecord.setUsername(dlsUser.getNickname());
        changeRecord.setRemark("代理商【" + dlsUser.getNickname() + "】 给网格 【" + wgUser.getNickname() + "】 分配金额, 分配之前代理商余额为: " 
        		+ AppUtil.doubleSplit((double)dlsMoney/100) + "元, 分配之后为: " + AppUtil.doubleSplit((double)dlsUser.getMoney()/100) + "元, 网格用户ID: " + wgUser.getId() + ", 手机号: " + wgUser.getPhone());
        sqlService.save(changeRecord);

        // 添加网格的金额变更记录
        MoneyChangeRecord wgChangeRecord = new MoneyChangeRecord();
        wgChangeRecord.setCreateTime(DateUtil.timeForUnix10());
        wgChangeRecord.setMoney(money);
        wgChangeRecord.setPhone(wgUser.getPhone());
        wgChangeRecord.setUserId(wgUser.getId());
        wgChangeRecord.setUsername(wgUser.getNickname());
        wgChangeRecord.setRemark("代理商【" + dlsUser.getNickname() + "】 给网格 【" + wgUser.getNickname() + "】 分配金额, 分配之前网格余额为: " 
        		+ AppUtil.doubleSplit((double)wgMoney/100)  + "元, 分配之后为: "+ AppUtil.doubleSplit((double)wgUser.getMoney()/100)  + "元, 网格用户ID: " + wgUser.getId() + ", 手机号: " + wgUser.getPhone());
        sqlService.save(wgChangeRecord);

        ActionLogUtil.insertUpdateDatabase(request, userId, "给网格ID为: " + wanggeUserid + "的网格分配金额,代理商金额变更记录为: " + changeRecord.toString() 
        + "网格金额变更记录为: " + wgChangeRecord.toString());
        return success();
    }



    /**
     * 进入代理商充值页面
     * @author zxy
     */
    @RequestMapping("recharge${url.suffix}")
    public String recharge(HttpServletRequest request,Model model){
        //获取代理商id
        int id = getUserId();
        model.addAttribute("id",id);
        //找出这个代理商
        Agency agency = sqlService.findAloneByProperty(Agency.class, "userid", id);
        int yue = agency.getMoney();
        model.addAttribute("yue",yue);
        //最低充值额度 单位 元
        int zuidiMoneyY = 100;
        model.addAttribute("zuidiMoneyY", zuidiMoneyY);
        //日志插入
        ActionLogUtil.insert(request, "财务管理 - 充值");
        return "/agency/finance/recharge";
    }



    /**
     * 代理商充值
     * @param money		充值的金额,单位:分
     */
//    @Transactional
    @ResponseBody
    @RequestMapping("rechargeLog${api.suffix}")
    public com.xnx3.BaseVO rechargeLog(HttpServletRequest request,
        @RequestParam(value = "money",required = true,defaultValue = "0") Integer money){

        int userId = getUserId();
        User user = sqlService.findById(User.class, userId);
        if (user == null) {
            return notLogin();
        }

        //最低充值额度 单位 元
        int zuidiMoneyY = 100;
        int zuidiMoneyF = zuidiMoneyY * 100;
        //对输入的金额做判断
        if (money < zuidiMoneyF) {
            return error("最小充值金额为" + zuidiMoneyY + "元");
        }
        // 代理商延伸表
        Agency agency = sqlService.findAloneByProperty(Agency.class, "userid", userId);
        if (agency == null ) {
            return notLogin();
        }
        // 获取用户绑定公众号信息
        WeixinPublicDlsOpenid weixinPublicDlsOpenid = sqlService.findAloneByProperty(WeixinPublicDlsOpenid.class, "userid", userId);
        if (weixinPublicDlsOpenid == null) {
            return error("请先绑定斑马回收公众号");
        }
        /**** 以下设置这笔支付的信息 ****/
        String openid = weixinPublicDlsOpenid.getOpenid();		//用户微信的openid
        // 32位订单号
        String no = UUID.randomUUID().toString().replaceAll("-", "");
        no = no.substring(13) + DateUtil.timeForUnix13();

        //扣去手续费之后 手续费是 0.6%
        int jingMoney = (int) (money - money * 0.006);
        // 创建充值记录
        RechargeLog log = new RechargeLog();
        log.setAddtime(DateUtil.timeForUnix10());
        log.setChannel("wx");
        log.setMoney(jingMoney);
        log.setOrderno(no);
        log.setPhone(user.getPhone());
        log.setRemark("代理商【" + agency.getName() + "】使用二维码进行余额充值,充值金额【" + money + "】分,扣去手续费【" + money * 0.006 + "】分");
        log.setState((short) 0);
        log.setUserid(userId);
        log.setUsername(user.getNickname());
        sqlService.save(log);
        ConsoleUtil.info("代理商【" + agency.getName() + "】使用二维码进行余额充值,充值金额【" + money + "】分,扣去手续费【" + money * 0.006 + "】分" + log.toString());
        // 日志
        ActionLogUtil.insertUpdateDatabase(request, userId, "代理商充值", "代理商【" + agency.getName() + "】使用二维码进行余额充值,充值金额【" + jingMoney + "】分" + log.toString());
        // 创建充值链接
        com.xnx3.BaseVO vo = pay.createOrder(openid, "代理商充值余额", money, no, request.getLocalAddr());
        return vo;
    }




    /**
     * 微信支付的回调。微信支付成功后，微信服务器会自动请求这个接口，将成功的订单号、支付了多少钱，传过来
     */
    @RequestMapping(value="callback.do")
    @ResponseBody
    public String callback(HttpServletRequest request) {
        PayCallBackParamsVO vo = pay.callback(request);
        if(vo.getResult() - PayCallBackParamsVO.FAILURE == 0) {
            //失败，可能是签名验证、伪造、恶意请求。。。等造成的，控制台打印一下失败原因
            ConsoleUtil.error(vo.getInfo());
            return "failure";
        }
        // 验证成功,查找到该笔订单
        RechargeLog rechargeLog = sqlService.findAloneByProperty(RechargeLog.class, "orderno", vo.getOutTradeNo());
        if (rechargeLog == null) {
            // 日志
            ActionLogUtil.insertUpdateDatabase(request, vo.getOutTradeNo(), "微信充值回调失败,未找到充值记录");
            return "failure";
        }
        User user = sqlService.findById(User.class, rechargeLog.getUserid());
        if (user == null) {
            // 日志
            ActionLogUtil.insertUpdateDatabase(request, vo.getOutTradeNo(), "微信充值回调失败,未找到充值记录中的用户信息");
            return "failure";
        }
        Agency agency = sqlService.findAloneByProperty(Agency.class,"userid", rechargeLog.getUserid());
        if (agency == null) {
            // 日志
            ActionLogUtil.insertUpdateDatabase(request, vo.getOutTradeNo(), "微信充值回调失败,未找到充值记录中的代理商信息");
            return "failure";
        }
        int nowtime = DateUtil.timeForUnix10();
        // 修改充值记录信息
        rechargeLog.setPaytime(nowtime);
        rechargeLog.setState((short) 1);
        JSONObject jsonObject = JSONObject.fromObject(vo.getParams());
        rechargeLog.setTradePayId(jsonObject.getString("transaction_id"));
        sqlService.save(rechargeLog);
        // 修改用户余额 
        //充值的金额 扣去手续费了
        int money = rechargeLog.getMoney();
        user.setMoney(user.getMoney() + money);
        sqlService.save(user);
        // 用户充值之前的金额
        Integer moneyInteger = agency.getMoney() == null ? 0 : agency.getMoney();
        agency.setMoney(moneyInteger + money);
        sqlService.save(agency);

        // 添加余额变更记录
        MoneyChangeRecord record = new MoneyChangeRecord();
        record.setCreateTime(nowtime);
        record.setMoney(money);
        record.setPhone(user.getPhone());
        record.setUserId(user.getId());
        record.setUsername(agency.getName());
        record.setRemark("代理商【" + agency.getName() + "】使用二维码进行余额充值,充值之前用户余额为: " 
        		+ AppUtil.doubleSplit((double)moneyInteger/100) + "元, 充值后为: " + AppUtil.doubleSplit((double)user.getMoney()/100) + "元,  充值记录信息ID: " + rechargeLog.getId() + ", 微信支付订单号: " + rechargeLog.getTradePayId());
        sqlService.save(record);
        // 日志
        ActionLogUtil.insertUpdateDatabase(request, vo.getOutTradeNo(), "微信充值回调成功,充值记录: " + rechargeLog.toString() + " 余额变更记录: " + record.toString());
        //记得处理成功要返回这个，告诉微信支付，我已经知道了，不要再推给我此订单支付成功的信息了
        return NativePay.callbackExecuteSuccess();
    }

}
